package me.flyray.bsin.oss.ipfs;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sofa.common.utils.StringUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import io.ipfs.api.Multipart;
import io.ipfs.api.NamedStreamable;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class BsinIpfsService {

    @Value("${bsin.s11edao.ipfs.api}")
    private String ipfsApi;
    @Value("${bsin.s11edao.ipfs.gateway}")
    private String ipfsGateway;

    /**
     * 将文件上传到ipfs服务节点上
     *
     * @param bytes
     * @param fileName
     * @return
     * @throws IOException
     */
    public JSONObject ipfsAdd(byte[] bytes, String fileName) throws IOException {

        String apiName = "/add";
        String url = ipfsApi + apiName;
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String newUUID = UUID.randomUUID().toString().replaceAll("-", "");
        String newFileName = newUUID + suffixName;
        Multipart m = new Multipart(url, "UTF-8");
        NamedStreamable.ByteArrayWrapper filew = new NamedStreamable.ByteArrayWrapper(newFileName, bytes);
        m.addFilePart(fileName, Paths.get(""), filew);
        String res = m.finish();
        JSONObject result = JSONObject.parseObject(res);
        String Hash = result.get("Hash").toString();
        result.put("fileUrl", ipfsGateway + Hash);
        result.put("fileHash", Hash);
        return result;
    }

    public String mkDir(String dirpath) throws IOException {
        //http://ipfsadmin.daxiongmao.art/api/v0/files/mkdir?parents=true&arg=%2F1
        String apiName = "/files/mkdir";
        String argument = "arg=" + dirpath + "&parents=true";
        String url = ipfsApi + apiName + "?" + argument;
        System.out.println(url);
        Multipart cpm = new Multipart(url, "UTF-8");
        return cpm.finish();
    }

    public JSONObject fileStat(String currentPath) throws IOException {

        String apiName = "/files/stat";
        String argument = "arg=" + currentPath;
        String url = ipfsApi + apiName + "?" + argument;
        //System.out.println(url);
        Multipart cpm = new Multipart(url, "UTF-8");
        try {
            String req = cpm.finish();
            return JSONObject.parseObject(req);
        } catch (RuntimeException e) {
            this.mkDir(currentPath);
            String req = new Multipart(url, "UTF-8").finish();
            return JSONObject.parseObject(req);
        }
    }

    public JSONObject fileLS(String hashDir) throws IOException {
        String apiName = "/ls";
        String argument = "arg=" + hashDir;
        String url = ipfsApi + apiName + "?" + argument;
        //System.out.println(url);
        Multipart cpm = new Multipart(url, "UTF-8");
        String req = cpm.finish();
        JSONObject result = JSONObject.parseObject(req);
        Object objs = result.getJSONArray("Objects").get(0);
        if (objs instanceof JSONObject) {
            JSONArray links = ((JSONObject) objs).getJSONArray("Links");
            for (Object e : links) {
                if (e instanceof JSONObject) {
                    ((JSONObject) e).put("Url", ipfsGateway + ((Map) e).get("Hash").toString());
                }
            }
        }
        return result;
    }

    public void ipfdCP(String hash, String currentPath, String filename) throws IOException {
        String cpTarget = currentPath + "/" + filename;
        String apiName = "/files/cp";
        String arguments = "arg=%s&arg=%s";
        String fileHash = "/ipfs/" + hash;
        String argument = String.format(arguments, fileHash, cpTarget);
        String url = ipfsApi + apiName + "?" + argument;
        //System.out.println(url);
        Multipart cpm = new Multipart(url, "UTF-8");
        cpm.finish();
    }

}
